package cn.mesmile.thread.lock;

import lombok.SneakyThrows;

/**
 * @author zb
 * @date 2020/12/31 15:01
 * @Description 出现死锁的情况
 *
 *      避免出现死锁：
 *          1.减少变量之间的共享
 *          2.尽量避免锁的嵌套使用
 */
public class Deadlock {

    public static void main(String[] args){

        final StringBuffer s1 = new StringBuffer();
        final StringBuffer s2 = new StringBuffer();


        new Thread(){
            @SneakyThrows
            @Override
            public void run() {
                //先拿锁一，再拿锁二
                synchronized (s1){
                    s1.append("a");
                    s2.append("1");
                    Thread.sleep(1000L);
                    synchronized (s2) {
                        s1.append("b");
                        s2.append("2");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();

        //使用匿名内部类实现runnable接口的方式实现线程的创建
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2){
                    s1.append("c");
                    s2.append("3");

                    synchronized (s1) {
                        s1.append("d");
                        s2.append("4");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}
